package net.ljh.controller;

import net.ljh.bean.User;
import net.ljh.service.UserService;
import net.ljh.utils.DateStyle;
import net.ljh.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
public class UserController {

    @Autowired
    UserService userService;

    //.ftl文件无法直接被访问,需要通过类跳转到页面

    @RequestMapping("/admin_toLogin")
    public String toLogin(){
        return "adminLogin";
    }

    //管理员登录
    @RequestMapping("/admin_login")
    public String Login(String name, String password, HttpSession session, HttpServletRequest request){
        User user=userService.login(name,password);
        System.out.println("--1--"+user);
        if (user==null){

            return "adminLogin";
        }else{

            session.setAttribute("userinfo",user);
            session.setAttribute("loginIp",request.getRemoteHost());
            session.setAttribute("loginTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));

            return "admin/index";
        }
    }

    @RequestMapping("/admin/logout")
    public String update(HttpSession session){
        User user= (User) session.getAttribute("userinfo");
        String ip= (String) session.getAttribute("loginIp");
        String time= (String) session.getAttribute("loginTime");
        user.setLastLoginIp(ip);
        user.setLastLoginTime(time);
       userService.update(user);
        session.removeAttribute("userinfo");
        return "adminLogin";


    }
}
